package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"github.com/tidwall/gjson"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"ginweb/system"
	log "github.com/sirupsen/logrus"
	"golang.org/x/crypto/bcrypt"
	"time"
	commomController "ginweb/app/common/controller"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/contrib/sessions"
)

type User struct {
	//gorm.Model
	ID int `gorm:"column:id;primary_key"`
	Username string
	Password string
} 

func Login(c *gin.Context)  {
	c.HTML(http.StatusOK, "console/login/index.html", gin.H{"msg":"我是console的模板哦"})
}
func Auth(c *gin.Context)  {
	username :=  c.PostForm("username")
	password :=  c.PostForm("password")
	commomController.ConfigLocalFilesystemLogger(system.GetConfiguration().LogPath, "auth.log", 7*24*time.Hour, 24*time.Hour)
	db, err := gorm.Open("mysql", system.GetConfiguration().DSN)
	if err != nil {
		log.Error("mysql连接失败：", err)
		c.JSON(200,gin.H{"code":41003})
	}
	defer db.Close()
	db.AutoMigrate(&User{})
	var user User

	userInfo := db.Where("username = ?", username).First(&user)
	if userInfo.Error != nil {
		log.Info(userInfo.Error)
		c.JSON(200,gin.H{"code":41002})
	}
	//读取数据 user.Username
	pwdErr := bcrypt.CompareHashAndPassword([]byte(string(user.Password)), []byte(password))
	if pwdErr != nil {
		log.Error("账号或者密码错误：【" + username + "】")
		c.Redirect(http.StatusMovedPermanently,"login")
	} else {
		session := sessions.Default(c)
		session.Set("user_id", user.ID)
		session.Save()
		c.Redirect(http.StatusMovedPermanently,"index")
	}
}
func Auth2(c *gin.Context)  {
	bytes, err := c.GetRawData()
	if err != nil {
		ResponseError(c, err)
		return
	}
	data := string(bytes)
	var username string
	var password string
	value := gjson.Get(data, "Username")
	if value.Index != 0 {
		username = value.String()
	} else {
		ResponseError(c, fmt.Errorf("Error:Username can not be empty!"))
		return
	}
	valuePwd := gjson.Get(data, "Password")
	if valuePwd.Index != 0 {
		password = valuePwd.String()
	} else {
		ResponseError(c, fmt.Errorf("Error:Password can not be empty!"))
		return
	}

	commomController.ConfigLocalFilesystemLogger(system.GetConfiguration().LogPath, "auth.log", 7*24*time.Hour, 24*time.Hour)
	db, err := gorm.Open("mysql", system.GetConfiguration().DSN)
	if err != nil {
		log.Error("mysql连接失败：", err)
		c.JSON(200,gin.H{"code":41003})
	}
	defer db.Close()
	db.AutoMigrate(&User{})

	//encodePwd,err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	//if err != nil {
	//	fmt.Println(encodePwd)
	//}
	//fmt.Println(string(encodePwd))
	////创建
	//insert := User{Username:"admin", Password:string(encode_pwd)}
	//db.Create(&insert)
	//c.JSON(200,gin.H{"status":"ok"})
	var user User

	userInfo := db.Where("username = ?", username).First(&user)
	if userInfo.Error != nil {
		log.Info(userInfo.Error)
		c.JSON(200,gin.H{"code":41002})
	}
	//读取数据 user.Username
	pwdErr := bcrypt.CompareHashAndPassword([]byte(string(user.Password)), []byte(password))
	if pwdErr != nil {
		c.JSON(200,gin.H{"code":41001})
	} else {
		userToken := setToken()
		c.JSON(200,gin.H{"code":200, "url":"index", "token":userToken})
	}

}

func ResponseError(c *gin.Context, err error) {
	fmt.Println(err)
	c.JSON(http.StatusOK, gin.H{
		"status": gin.H{
			"code":  http.StatusBadRequest,
			"message": err.Error(),
		},
	})
}

func setToken() string {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Add(time.Hour * time.Duration(1)).Unix()
	claims["iat"] = time.Now().Unix()
	token.Claims = claims
	tokenString, err := token.SignedString([]byte("mobile"))
	if err != nil {
		return ""
	}
	return tokenString
}